// Copyright (c) 2020 Presto Labs Pte. Ltd.
// Author: chunhui

#include <glog/logging.h>

#include "cc/appcoin2/support/feed/interval_feed_tool/util.h"
#include "coin2/base/date_util.h"

namespace interval_feed {

namespace fs = std::experimental::filesystem;

void GetIntervalFeedPathOrDie(
    const std::string& root,
    const std::string& vendor,
    const std::string& machine,
    const std::string& resolution,
    const std::string& mea,
    const std::string& date,
    std::string* out) {
  fs::path filepath = root;
  std::string ymd_str = date;

  size_t T_position = date.find("T");
  if (T_position != std::string::npos) {
    ymd_str = date.substr(0,T_position);
  }
  CHECK(filepath.has_root_path()) << "File path should be absolute";
  CHECK(coin2::exchange::base::symbology::IsDateStr(ymd_str)) << "Invalid date " << date;

  filepath /= vendor;
  filepath /= machine;
  filepath /= resolution;
  filepath /= mea;
  filepath /= date;

  if (!fs::is_directory(filepath)) {
    LOG(INFO) << "Try to create directory " << filepath;
    CHECK(fs::create_directories(filepath))
        << "Fail to create directory " << filepath;
  }

  // TODO(chunhui): determine a better universe name
  const std::string& universe = mea;
  filepath /= universe;
  *out = filepath.string();
}

void GetResolutionStr(int resolution, std::string* out) {
  const int sec_in_min = 60;
  const int min_in_hr = 60;
  const int hr_in_day = 24;
  std::stringstream resolution_str;
  int day = resolution / (sec_in_min * min_in_hr * hr_in_day);
  resolution_str << "P";
  if (day > 0) {
    resolution_str << day << "D";
    resolution -= day * sec_in_min * min_in_hr * hr_in_day;
  }
  resolution_str << "T";
  int hour = resolution / (sec_in_min * min_in_hr);
  if (hour > 0) {
    resolution_str << hour << "H";
    resolution -= hour * sec_in_min * min_in_hr;
  }
  int minute = resolution / sec_in_min;
  if (minute > 0) {
    resolution_str << minute << "M";
    resolution -= minute * sec_in_min;
  }
  int second = resolution;
  if (second > 0) {
    resolution_str << second << "S";
  }
  *out = resolution_str.str();
}

}  // namespace interval_feed
